package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.*;
import cn.wolfcode.wms.mapper.ProductStockMapper;
import cn.wolfcode.wms.mapper.SaleAccountMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IStockOutcomeBillService;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService{

    @Autowired
    private StockOutcomeBillMapper billMapper;
    @Autowired
    private StockOutcomeBillItemMapper itemMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private SaleAccountMapper saleAccountMapper;

    public void saveOrUpdate(StockOutcomeBill entity) {

        //判断是保存还是添加操作
        if (entity.getId() == null) {
           insert(entity);
        }else{
            update(entity);
        }
    }

    //保存的方法
    private void insert(StockOutcomeBill entity) {
        //设置录入人(当前登陆的用户)
        entity.setInputUser(UserContext.getCurrentUser());
        //设置录入时间
        entity.setInputTime(new Date());
        //设置状态(未审核)
        entity.setStatus(StockOutcomeBill.NORMAL);
        //定义两个变量.用来计算总数量和总金额
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        //计算小计
        for (StockOutcomeBillItem item : entity.getItems()) {
            //获取商品价格
            BigDecimal costPrice = item.getSalePrice();
            //获取商品的数量
            BigDecimal number = item.getNumber();
            BigDecimal amount = costPrice.multiply(number).setScale(2, RoundingMode.HALF_UP);
            //设置小计
            item.setAmount(amount);
            //计算总数量和总金额
            totalAmount = totalAmount.add(amount);
            totalNumber = totalNumber.add(number);
        }
        //设置总金额和总数量
        entity.setTotalAmount(totalAmount);
        entity.setTotalNumber(totalNumber);

        //先保存库存,在保存明细
        billMapper.insert(entity);

        //在保存操作中,最后才能保存明细
        for (StockOutcomeBillItem item : entity.getItems()) {
            //设置id
            item.setBillId(entity.getId());
            itemMapper.insert(item);
        }
    }

    //更新的方法
    private void update(StockOutcomeBill entity) {
        //判断是否已经审核了,只有没有审核才能更新
        StockOutcomeBill old = billMapper.selectByPrimaryKey(entity.getId());
        if (old.getStatus() == StockOutcomeBill.NORMAL) {
            //先删除之前对应的所有明细
            billMapper.deleteByRelation(old.getId());
            //定义两个变量,表示总金额和总数量
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            //迭代出所有的明细
            for (StockOutcomeBillItem item : entity.getItems()) {
                BigDecimal salePrice = item.getSalePrice();
                BigDecimal number = item.getNumber();
                BigDecimal amount = salePrice.multiply(number).setScale(2,RoundingMode.HALF_UP);
                item.setAmount(amount);
                totalAmount = totalAmount.add(amount);
                totalNumber = totalNumber.add(number);
                //保存明细
                item.setBillId(entity.getId());
                itemMapper.insert(item);
            }
            entity.setTotalNumber(totalNumber);
            entity.setTotalAmount(totalAmount);
            billMapper.updateByPrimaryKey(entity);
        }
    }

    public void delete(Long id) {
        //先删除明细
        billMapper.deleteByRelation(id);
        billMapper.deleteByPrimaryKey(id);
    }

    public StockOutcomeBill get(Long id) {

        return billMapper.selectByPrimaryKey(id);
    }

    public PageResult queryResult(QueryObject qo) {
        Integer rows = billMapper.queryForCount(qo);
        //判断数据库中的记录数是否为null
        if (rows==0) {
            return PageResult.EMPRY_PAGE;
        }
        //===============
        //如果数据库中有数据
        List<StockOutcomeBill> data = billMapper.queryForPage(qo);
        return new PageResult(data,rows,qo.getCurrentPage(),qo.getPageSize());
    }

    //审核的方法(好,我们来开始审核了)
    public void audit(Long id) {
        //判断当前的单据是否已经审核了,如果没有审核,那么就进去审核,如果审核了,那么此时就不需要在审核了
        StockOutcomeBill incomeBill = billMapper.selectByPrimaryKey(id);
        if (incomeBill.getStatus() == StockOutcomeBill.NORMAL) {
            //获取入库单存储的仓库
            Depot depot = incomeBill.getDepot();
            //迭代出入库单中所有的明细,依次添加到库存中
            for (StockOutcomeBillItem item : incomeBill.getItems()) {
                //获取明细中的商品
                Product product = item.getProduct();
                //=========销售出库=========
                //查询库存中是否有该商品的存在
                ProductStock stock = productStockMapper.selectByProductAndDepot(product.getId(), depot.getId());
                if (stock == null) {//库存中没有该商品
                    String msg = depot.getName()+"仓库中没有"+product.getName()+"商品的库存";
                    //抛出异常
                    throw new RuntimeException(msg);
                }
                //当需求大于库存时
                if (item.getNumber().compareTo(stock.getStoreNumber())>0) {

                    String msg = "该商品库存数量不足"+item.getNumber();
                    //抛异常
                    throw new RuntimeException(msg);
                }
                //减少库存,减少总金额
                BigDecimal am = stock.getPrice().multiply(item.getNumber())
                        .setScale(2, RoundingMode.HALF_UP);//购买这个商品的总额
                //库存总额减商品总额
                 BigDecimal amount = stock.getAmount().subtract(am);
                //设置库存总额
                stock.setAmount(amount);
                BigDecimal storeNumber = stock.getStoreNumber()
                        .subtract(item.getNumber());
                //设置库存数量
                stock.setStoreNumber(storeNumber);
                //更新库存
                productStockMapper.updateByPrimaryKey(stock);
                //==========记录销售帐=================
                SaleAccount sale = new SaleAccount();
                //商品销售成本价
                sale.setCostAmount(am);
                //商品成本价
                sale.setCostPrice(stock.getPrice());
                //商品个数
                sale.setNumber(item.getNumber());
                //销售时间
                sale.setVdate(new Date());
                //销售的商品
                sale.setProduct(item.getProduct());
                //销售员
                sale.setSaleman(incomeBill.getInputUser());
                //客户
                sale.setClient(incomeBill.getClient());
                //商品零售价
                sale.setSalePrice(item.getSalePrice());
                //商品零售总额
                sale.setSaleAmount(item.getSalePrice().multiply(item.getNumber()));
                //保存销售帐
                saleAccountMapper.insert(sale);

                //===============保存账单完毕================
            }
            //设置审核时间
            incomeBill.setAuditTime(new Date());
            //设置审核人
            incomeBill.setAuditor(UserContext.getCurrentUser());
            //改变审核状态
            incomeBill.setStatus(StockOutcomeBill.AUDIT);
            //最后是审核单据
            billMapper.audit(incomeBill);
        }

    }

}
